<template>
  <div>
    <button @click="handlePrints">打印</button>
    <div ref="filePath" id="printDiv">
      <div v-for="(item, index) in filePath" :key="index">
        <div :ref="'filePath' + index" style="color: #f00;">
          我的打印内容；{{ item }}
        </div>
      </div>
    </div>
  </div>
</template>
<script>
//为了静默打印
import { io } from "socket.io-client";
export default {
  data() {
    return {
      ids: [], //存储获取的id
      hiprintTemplate: "",
      filePath: ["11111", "2222222", "测试测试测试"],
      socket: ""
    };
  },
  created() {
    //为了静默打印  //连接静默打印客户端
    // this.socket = io("http://2.0.0.1:17521", {
    //   transports: ["websocket"],
    //   auth: {
    //     token: "vue-plugin-hiprint" // 在此处填入你 client 设置的 token，缺省可留空
    //   }
    // });
    // //连接成功
    // this.socket.on("connect", () => {
    //   console.log("connect");
    // });
    // //连接断开
    // this.socket.on("disconnect", () => {
    //   console.log("disconnect");
    // });
    // //获取打印机列表
    // this.socket.on("printerList", printerList => {
    //   console.log("printerList", printerList);
    // });
    // //连接错误
    // this.socket.on("connect_error", error => {
    //   console.error("Connection error:", error);
    // });
  },
  mounted() {
    this.$nextTick(() => {
      //打印
      const hiprintTemplate_ = new this.$pluginName.PrintTemplate();
      this.hiprintTemplate = hiprintTemplate_;
      // const printerList = hiprintTemplate_.getPrinterList();
      // console.info("打印机列表", printerList);
    });
  },
  methods: {
    handlePrints(row) {
      let that = this;
      const ids = that.ids;
      //这是我的后端接口
      // downloadOneReimbursement(ids).then(res => {
      // 	that.filePath = res.data.url //我这是一个数组，后端给的地址，我通过在线地址展示成div
      // })
      //直接打印其实就是将填充完数据的html 通过socket.io连接发送到直接打印客户端
      setTimeout(function() {
        that
          .$confirm("是否立即打印?", "警告", {
            confirmButtonText: "预览打印",
            cancelButtonText: "静默打印",
            type: "warning"
          })
          .then(function() {
            //预览打印
            that.hiprintTemplate.printByHtml(that.$refs.filePath, {});
          })
          .catch(() => {
            //静默打印
            that.filePath.forEach((item, index) => {
              let ins = "filePath" + index;
              //获取html
              let html = that.$refs[ins][0].outerHTML;

              that.hiprintTemplate.printByHtml2(that.$refs.filePath, {
                //跳过预览直接打印
                // printer: "NPIF6D7F6 (HP Color LaserJet Pro M252dw)",
                html,
                color: false, // 是否打印颜色 默认 true
                copies: 1 // 打印份数 默认 1
              });
            });
          });
      }, 400);
    }
  }
};
</script>
